﻿////#define DEBUG_SCHEDULE

namespace USElections.Classes
{
    using System;
    using System.Diagnostics;
    using Microsoft.Phone.Scheduler;
    using USElections.Model;

    /// <summary>
    /// ScheduledAgentTools class.
    /// </summary>
    public static class ScheduledAgentTools
    {
        /// <summary>
        /// Start a Periodic agent.
        /// </summary>
        /// <param name="taskname">The taskname.</param>
        /// <param name="description">The task description.</param>
        public static void StartPeriodicAgent(Enums.PeriodicTaskName taskname, string description)
        {
            PeriodicTask periodicTask = ScheduledActionService.Find(taskname.ToString()) as PeriodicTask;

            if (periodicTask != null)
            {
                ScheduledAgentTools.RemoveAgent(taskname);
            }

            periodicTask = new PeriodicTask(taskname.ToString());

            periodicTask.Description = description;

            try
            {
                ScheduledActionService.Add(periodicTask);

#if DEBUG_SCHEDULE
                ScheduledActionService.LaunchForTest(taskname.ToString(), TimeSpan.FromSeconds(10));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    Debug.WriteLine(string.Format("Unable to start periodicTask: {0}.", taskname));
                }
            }
        }

        /// <summary>
        /// Start a Resource Intensive agent.
        /// </summary>
        /// <param name="taskname">The taskname.</param>
        /// <param name="description">The task description.</param>
        public static void StartResourceIntensiveAgent(Enums.ResourceIntensiveTaskName taskname, string description)
        {
            ResourceIntensiveTask resourceIntensiveTask = ScheduledActionService.Find(taskname.ToString()) as ResourceIntensiveTask;

            if (resourceIntensiveTask != null)
            {
                ScheduledAgentTools.RemoveAgent(taskname);
            }

            resourceIntensiveTask = new ResourceIntensiveTask(taskname.ToString());

            resourceIntensiveTask.Description = description;

            try
            {
                ScheduledActionService.Add(resourceIntensiveTask);

#if DEBUG_SCHEDULE
                ScheduledActionService.LaunchForTest(taskname.ToString(), TimeSpan.FromSeconds(10));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    Debug.WriteLine(string.Format("Unable to start resourceIntensiveTask: {0}.", taskname));
                }
            }
        }

        /// <summary>
        /// Remove a background task.
        /// </summary>
        /// <param name="taskname">The taskname.</param>
        public static void RemoveAgent(Enums.PeriodicTaskName taskname)
        {
            try
            {
                ScheduledActionService.Remove(taskname.ToString());
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// Remove a background task.
        /// </summary>
        /// <param name="taskname">The taskname.</param>
        public static void RemoveAgent(Enums.ResourceIntensiveTaskName taskname)
        {
            try
            {
                ScheduledActionService.Remove(taskname.ToString());
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// Get a value indicating whether the background task is allowed to start.
        /// </summary>
        /// <param name="taskname">The taskname.</param>
        /// <returns>True if allowed to start.</returns>
        public static bool GetAllowedToStart(Enums.PeriodicTaskName taskname)
        {
            string value = NorthernLights.PersistentVariables.Get<string>(string.Format("{0}_{1}", Model.Enums.Variables.Tasks, taskname));

            if (string.IsNullOrEmpty(value) || value == "1")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Set a value indicating whether the background task is allowed to start.
        /// </summary>
        /// <param name="taskname">The taskname.</param>
        /// <param name="description">The task description.</param>
        /// <param name="value">The value to set.</param>
        public static void SetAllowedToStart(Enums.PeriodicTaskName taskname, string description, bool value)
        {
            if (value)
            {
                NorthernLights.PersistentVariables.Set<string>(string.Format("{0}_{1}", Model.Enums.Variables.Tasks, taskname), "1");
                StartPeriodicAgent(taskname, description);
            }
            else
            {
                NorthernLights.PersistentVariables.Set<string>(string.Format("{0}_{1}", Model.Enums.Variables.Tasks, taskname), "0");
                RemoveAgent(taskname);
            }
        }
    }
}
